package com.chwn.curiousdiary.ui.user.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.bean.StoryBean;
import com.chwn.curiousdiary.download.DownService;
import com.chwn.curiousdiary.download.DownloadBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.provider.DownloadStoryStore;
import com.chwn.curiousdiary.service.AudioService;
import com.chwn.curiousdiary.ui.play.activity.StoryPlayActivity;
import com.chwn.curiousdiary.ui.user.presenter.DownLoadPresenter;
import com.chwn.curiousdiary.ui.user.contract.DownLoadContract;
import com.chwn.curiousdiary.utils.FileUtils;
import com.chwn.curiousdiary.utils.ImgLoadUtil;
import com.chwn.curiousdiary.widget.HoloCircularProgressBar;
import com.chwn.curiousdiary.widget.ItemRemoveRecyclerView;
import com.chwn.curiousdiary.widget.OnItemClickListener;
import com.chwn.harulib.mvp.base.BaseMVPFragment;
import com.chwn.harulib.util.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Myshikin on 2017/4/27.
 */
public class DownloadFragment extends BaseMVPFragment<DownLoadPresenter> implements DownLoadContract.View {

    @BindView(R.id.rv_content)
    ItemRemoveRecyclerView mContentRV;


    private ArrayList<DownloadBean> mList = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private DownLoadAdapter     adapter;
    private DownloadStoryStore  downFileStore;
    private DownStatus          downStatus;
    private int downPosition = -1;

    @Override
    public void showDownLoadStories(List<DownloadBean> data) {

    }

    @Override
    public void onStart() {
        super.onStart();
        downStatus = new DownStatus();
        IntentFilter f = new IntentFilter();
        f.addAction(DownService.TASK_STARTDOWN);
        f.addAction(DownService.UPDATE_DOWNSTAUS);
        f.addAction(DownService.TASKS_CHANGED);
        mActivity.registerReceiver(downStatus, new IntentFilter(f));
    }

    @Override
    public void onStop() {
        super.onStop();
        mActivity.unregisterReceiver(downStatus);
    }

    @Override
    protected int setContentViewId() {
        return R.layout.fragment_download;
    }

    @Override
    protected void initContentView() {
        ButterKnife.bind(this, mInflateContentView);
        layoutManager = new LinearLayoutManager(mActivity);
        mContentRV.setHasFixedSize(true);
        mContentRV.setLayoutManager(layoutManager);
        adapter = new DownLoadAdapter(null, null);
        mContentRV.setAdapter(adapter);
        mContentRV.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                gotoPlayPage(position);
            }

            @Override
            public void onDeleteClick(int position) {
                ToastUtil.shortShowToast("已删除");
                DownloadBean downloadBean = mList.get(position);
                Intent intent = new Intent(DownService.CANCLE_DOWNTASK);
                intent.putExtra("downloadid", downloadBean.getStoryId());
                intent.setPackage(Constant.PACKAGE_NAME);
                mActivity.startService(intent);
                File file = new File(downloadBean.getSaveDirPath(), downloadBean.getStoryName() + ".mp3");
                FileUtils.deleteFile(file);
                reload();
            }
        });
        showContentView();
        reload();
        initStateViewData();
    }

    private void initStateViewData() {
        setEmptyView(R.drawable.icon_no_collecte);
        setErrorView(R.drawable.icon_no_collecte);
        setErrorText("哎呀，快去检查一下网络吧～");
        setEmptyText("您还没有下载故事呢，赶紧去听吧～");
    }
    @Override
    protected void getData() {
        mIsFirst = false;
    }

    private void reload() {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                downFileStore = DownloadStoryStore.getInstance(mActivity);
                //                mList = downFileStore.getDownLoadedListAllDowning();
                mList = downFileStore.getDownLoadedListAll();

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                adapter.update(mList, DownService.getPrepareTasks());
                if (mList == null || mList.size() < 1) {
                    showEmptyView();
                } else {
                    showContentView();
                }
            }
        }.execute();
    }

    public class DownLoadAdapter extends RecyclerView.Adapter<DownLoadAdapter.ItemViewHolder> {

        private ArrayList         mList;
        private ArrayList<String> currentTaskList;
        private long completed = 0;
        private long totalsize = -1;


        public DownLoadAdapter(ArrayList list, ArrayList<String> currentTaskList) {
            mList = list;
            this.currentTaskList = currentTaskList;
        }

        public void update(ArrayList list, ArrayList<String> currentTaskList) {
            mList = list;
            this.currentTaskList = currentTaskList;
            completed = 0;
            totalsize = -1;
            notifyDataSetChanged();
        }

        public void notifyItem(long completed, long total) {
            this.completed = completed;
            if (total != -1)
                this.totalsize = total;
            notifyItemChanged(downPosition);
        }

        @Override
        public DownLoadAdapter.ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_down_item, parent, false));
        }

        @Override
        public void onBindViewHolder(final DownLoadAdapter.ItemViewHolder holder, final int position) {
            boolean isCurrent = false;
            boolean isPreparing = false;
            final DownloadBean task = (DownloadBean) mList.get(position);
            holder.storyNameTV.setText(task.getStoryName());
            holder.storyDescTV.setText(task.getStoryDesc());
            ImgLoadUtil.displayStoryImage(holder.storyImg, task.getStoryImage());

            if (currentTaskList.size() > 0) {
                isCurrent = currentTaskList.get(0).equals(task.getStoryId());
                if (isCurrent) {
                    downPosition = position;
                    mContentRV.addDowningPosition(downPosition);
                }else {
                    mContentRV.cancelDowningPosition(position);
                }
                if (currentTaskList.contains(task.getStoryId())) {
                    isPreparing = true;
                }
            }

            holder.leftTV.setText(task.getStoryListenCountString());
            holder.rightTV.setText(task.getStoryCreateTimeString());

            if (isCurrent) {
                completed = completed > task.getCompletedSize() ? completed : task.getCompletedSize();
                totalsize = totalsize > task.getTotalSize() ? totalsize : task.getTotalSize();

                if (totalsize > 0) {
                    holder.progressBar.setProgress((100 * completed / totalsize) / 100f);
                }else {
                    holder.progressBar.setProgress(0.0f);
                }
                if (holder.progressBar.getVisibility() != View.VISIBLE)
                    holder.progressBar.setVisibility(View.VISIBLE);
                    holder.downState.setVisibility(View.GONE);
            } else if (currentTaskList.contains(task.getStoryId())) {
                holder.downState.setVisibility(View.VISIBLE);
                holder.progressBar.setVisibility(View.GONE);
                holder.downState.setImageResource(R.drawable.icon_down_orange);
            } else {
                holder.downState.setVisibility(View.VISIBLE);
                holder.downState.setImageResource(R.drawable.icon_downed_orange);
                holder.progressBar.setVisibility(View.GONE);
                mContentRV.cancelDowningPosition(position);
            }



//            final boolean isCurrent1 = isCurrent;

            /*holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    gotoPlayPage(position);
                }
            });*/

           /* ((ItemViewHolder) holder).title.setText(task.getStoryName());

            if (isCurrent) {
                completed = completed > task.getCompletedSize() ? completed : task.getCompletedSize();
                totalsize = totalsize > task.getTotalSize() ? totalsize : task.getTotalSize();
                if (completed == 0 || totalsize == -1) {
                    ((ItemViewHolder) holder).count.setText("正在计算大小文件大小");
                    ((ItemViewHolder) holder).progressBar.setVisibility(View.GONE);
                } else {
                    ((ItemViewHolder) holder).count.setText((float) (Math.round((float) completed / (1024 * 1024) * 10)) / 10 + "M/" +
                            (float) (Math.round((float) totalsize / (1024 * 1024) * 10)) / 10 + "M");
                    if (((ItemViewHolder) holder).progressBar.getVisibility() != View.VISIBLE)
                        ((ItemViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
                    if (totalsize > 0)
                        ((ItemViewHolder) holder).progressBar.setProgress((int) (100 * completed / totalsize));
                }
            } else if (isPreparing) {
                ((ItemViewHolder) holder).progressBar.setVisibility(View.GONE);
                ((ItemViewHolder) holder).count.setText(task.getStoryName() + "-" + task.getStoryName());
            } else {
                ((ItemViewHolder) holder).progressBar.setVisibility(View.GONE);
                ((ItemViewHolder) holder).count.setText("已经暂停，点击继续下载");
            }

            final boolean isPreparing1 = isPreparing;
            ((ItemViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isPreparing1) {
                        Intent intent = new Intent(DownService.PAUSE_TASK);
                        intent.setPackage(Constant.PACKAGE_NAME);
                        intent.putExtra("downloadid", task.getStoryId());
                        mActivity.startService(intent);
                    } else {
                        Intent intent = new Intent(DownService.RESUME_START_DOWNTASK);
                        intent.setPackage(Constant.PACKAGE_NAME);
                        intent.putExtra("downloadid", task.getStoryId());
                        mActivity.startService(intent);
                    }

                }
            });

            ((ItemViewHolder) holder).clear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new AlertDialog.Builder(mActivity).setTitle("要清除下载吗")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(DownService.CANCLE_DOWNTASK);
                                    intent.putExtra("downloadid", task.getStoryId());
                                    intent.setPackage(Constant.PACKAGE_NAME);
                                    mActivity.startService(intent);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
                }
            });*/
        }

        @Override
        public int getItemCount() {
            return mList == null ? 0 : mList.size();
        }

        public class ItemViewHolder extends RecyclerView.ViewHolder {

            /*ImageView draweeView;
            ImageView downloaded, clear;
            TextView title, count, artist;*/
            HoloCircularProgressBar progressBar;
            ImageView               storyImg , downState;
            public TextView delete;
            TextView storyNameTV, storyDescTV , leftTV , rightTV;
            public LinearLayout layout;

            public ItemViewHolder(View itemView) {
                super(itemView);
                storyImg = (ImageView) itemView.findViewById(R.id.iv_story_img);
                storyNameTV = (TextView) itemView.findViewById(R.id.tv_story_name);
                storyDescTV = (TextView) itemView.findViewById(R.id.tv_story_desc);
                leftTV = (TextView) itemView.findViewById(R.id.tv_left);
                rightTV = (TextView) itemView.findViewById(R.id.tv_right);
                delete = (TextView) itemView.findViewById(R.id.item_delete);
                progressBar = (HoloCircularProgressBar) itemView.findViewById(R.id.down_progress);
                layout = (LinearLayout) itemView.findViewById(R.id.item_layout);
                downState = (ImageView) itemView.findViewById(R.id.down_state);
                /*draweeView = (ImageView) itemView.findViewById(R.id.iv_story_img);
                title = (TextView) itemView.findViewById(R.id.down_top_text);
                count = (TextView) itemView.findViewById(R.id.down_count);
                clear = (ImageView) itemView.findViewById(R.id.down_single_clear);
                artist = (TextView) itemView.findViewById(R.id.down_artist);
                downloaded = (ImageView) itemView.findViewById(R.id.downloaded);
                progressBar = (ProgressBar) itemView.findViewById(R.id.down_progress);*/
                progressBar.setProgress(1.0f);

                /*clear.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });*/

            }
        }


    }

    private void gotoPlayPage(int position) {
        ArrayList<DownloadBean> downingList = downFileStore.getDownLoadedListAllDowning();
        ArrayList<StoryBean> storyList = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            boolean isDownload = true;
            for (int j = 0; j < downingList.size(); j++) {
                if (mList.get(i).getStoryId().equals(downingList.get(j).getStoryId())) {
                    isDownload = false;
                }
            }
            DownloadBean downloadBean = mList.get(i);

            storyList.add(new StoryBean(
                    downloadBean.getStoryId(),
                    downloadBean.getStoryName(),
                    downloadBean.getStoryDesc(),
                    downloadBean.getStoryImage(),
                    isDownload ? downloadBean.getSaveDirPath() + downloadBean.getStoryName() + ".mp3" : downloadBean.getUrl(),
                    downloadBean.getStroyShareURL()
            ));
        }
        Intent intent = new Intent(getActivity(), StoryPlayActivity.class);
        intent.putExtra(Constant.STORY_SERVICE_TYPE, AudioService.HOME_ENTER);
        intent.putExtra(Constant.PACKAGE_ID, Constant.PACKAGE_ID);
        intent.putExtra("list", storyList);
        intent.putExtra("position", position);
        startActivity(intent);
    }

    private void getDownLoadedStory() {

    }

    private class DownStatus extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case DownService.UPDATE_DOWNSTAUS:
                    adapter.notifyItem(intent.getLongExtra("completesize", 0), intent.getLongExtra("totalsize", -1));
                    break;
                case DownService.TASK_STARTDOWN:
                    adapter.notifyItem(intent.getLongExtra("completesize", 0), intent.getLongExtra("totalsize", -1));
                    break;
                case DownService.TASKS_CHANGED:
                    reload();
                    break;

            }
        }
    }


}
